<template>
  <view class="bgf">
    <OrderStepBar
      :current="stepCurrentItem?.stepIndex"
      :is-current-step-err="currentStepErr"
      :step-list="stepList"
    />

    <view v-if="stepCurrentItem?.showLabel" class="pa-15">
      <view class="stepTips" @click="stepCurrentItem?.clickFnc">
        <view class="disFlxAC" style="flex: 1">
          <TImage
            v-if="stepCurrentItem?.labelImg"
            :src="stepCurrentItem?.labelImg"
            width="72rpx"
            height="72rpx"
            border-radius="10rpx"
          />
          <view
            class="pl-6 text-overflow-1"
            :style="{ color: stepCurrentItem?.labelColor || colors.default }"
          >
            <text>{{ stepCurrentItem?.label }}</text>
          </view>
        </view>

        <view :style="{ color: stepCurrentItem?.valueColor }">
          {{ stepCurrentItem?.value }}
        </view>
      </view>
    </view>
    <view
      class="refusal-cause pa-15"
      v-if="refusalText || refundStatus"
      :style="{ color: colors.error }"
    >
      <view v-if="refusalText">驳回原因：{{ refusalText }}</view>
      <view v-if="refundStatus" style="margin-bottom: 30rpx">
        {{ refundStatus === OrderRefundStatusEnum.REFUNDED ? '已退款' : '退款中' }}
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { countDown } from '@/utils/dateUtil';
  import {
    computed,
    type CSSProperties,
    onUnmounted,
    type PropType,
    type Ref,
    ref,
    unref,
    watchEffect,
  } from 'vue';
  import OrderStepBar from '../../components/OrderStepBar.vue';
  import {
    OrderAuditStateEnum,
    OrderPayStateEnum,
    OrderStateEnum,
    OrderRefundStatusEnum,
    GroupChatStateEnum,
  } from '@/enums/orderEnum';
  import { formatMoney } from '@/utils/number';
  import { propTypes } from '@/utils/propTypes';
  import { isNullOrUnDef } from '@/utils/is';
  import { isNaN } from 'lodash-es';
  import { SourceTypeEnum } from '@/enums/contactsEnum';
  import type { CreateSuborderResult } from '@/api/order/types';
  import TImage from '@/components/TImage/index.vue';
  import { navigateTo } from '@/router';

  const props = defineProps({
    orderState: Number as PropType<OrderStateEnum>,
    payState: Number as PropType<OrderPayStateEnum>,
    refundStatus: Number as PropType<OrderRefundStatusEnum>,
    suborder: Object as PropType<CreateSuborderResult>,
    price: propTypes.number.def(0),
    paymentEndTime: propTypes.string.def(''),
  });

  const emit = defineEmits(['refresh']);

  // 0预约 1待付款 2秘书处审核 3秘书处联络 4建立群聊 5已完成
  const stepList = computed(() => {
    return [
      {
        label: '填写需求',
        value: 0,
      },
      {
        label: '付款',
        value: 1,
      },
      {
        label: '秘书处审核',
        value: 2,
      },
      // 会外数据添加会外审核状态
      ...(props.suborder?.assType === SourceTypeEnum.OUTSIDE ||
      props.suborder?.assType === SourceTypeEnum.LEAGUE
        ? [
            {
              label: '秘书处联络',
              value: 3,
            },
          ]
        : []),
      {
        label: '对接完成',
        value: 4,
      },
    ];
  });

  const getStepListValue = (index: number) => unref(stepList)[index].value;

  const colors = {
    default: '#333',
    primary: '#2878ff',
    error: '#ff3434',
    close: '#AAABAB',
    price: '#b47026',
  };

  const currentStepErr = ref(false);

  interface StepItem {
    stepIndex: number;
    label: string;
    labelColor?: CSSProperties['color'];
    labelImg?: string;
    value?: string | Ref;
    valueColor?: CSSProperties['color'];
    showLabel?: boolean;
    clickFnc?: () => void;
  }

  const step = new Map<OrderStateEnum | 'default', () => StepItem>([
    [
      'default',
      () => {
        return {
          stepIndex: getStepListValue(0),
          label: '通过秘书处联络',
          value: `金额: ${formatMoney({ money: props.price, showFreeText: true })}`,
          showLabel: true,
          valueColor: colors.price,
        };
      },
    ],
    [
      OrderStateEnum.NOPAYMENT,
      () => {
        createTimer();
        return {
          stepIndex: getStepListValue(1),
          label: '待支付',
          showLabel: true,
          value: endTime.value,
          valueColor: colors.error,
        };
      },
    ],
    [
      OrderStateEnum.CLOSED,
      () => {
        clearInterval(unref(timerRef));
        currentStepErr.value = true;
        if (props.payState === OrderPayStateEnum.HAVEPAID) {
          return checkAuditState();
        } else {
          return {
            stepIndex: getStepListValue(1),
            label: '已关闭',
            showLabel: true,
            labelColor: colors.close,
          };
        }
      },
    ],
    [
      OrderStateEnum.UNDERWAY,
      () => {
        return checkAuditState();
      },
    ],
    [
      OrderStateEnum.DONE,
      () => {
        return {
          stepIndex: getStepListValue(unref(stepList).length - 1),
          label: '工作交流群',
          labelImg: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/obs/20230225/2d339919b68c4102b081aa6288bd4d70.png',
          value: '进入群聊',
          valueColor: '#333',
          showLabel: props.suborder?.groupChatState === GroupChatStateEnum.CREATED,
          clickFnc: () => {
            // 跳转群聊 - 会话ID
            props.suborder &&
              navigateTo({
                name: 'TUIChat',
                options: { conversationID: `GROUP${props.suborder.orderCode}` },
              });
          },
        };
      },
    ],
  ]);

  const stepCurrentItem = ref<StepItem>();
  watchEffect(() => {
    const state = props.orderState;
    stepCurrentItem.value = step.get(!isNullOrUnDef(state) ? state : 'default')?.() as StepItem;
  });

  const refusalText = computed(() => props.suborder?.toOrgAuditReason);
  /** 检查审核状态 */
  function checkAuditState(): StepItem {
    const item: StepItem = {
      stepIndex: 2,
      label: '',
      showLabel: true,
    };
    const suborder = props.suborder;
    if (!suborder) return item;
    if (
      (suborder?.assType === SourceTypeEnum.OUTSIDE ||
        suborder?.assType === SourceTypeEnum.LEAGUE) &&
      suborder?.orgAuditStatus === OrderAuditStateEnum.PASSED
    ) {
      // "秘书处联系中"的内容
      item.stepIndex = 3;
      item.labelImg = suborder.toOrgLogo;
      item.label = suborder.toOrgName;
      if (suborder.toOrgAuditStatus === OrderAuditStateEnum.REJECT) {
        item.value = '已驳回';
        item.valueColor = colors.error;
      }
      if (suborder.toOrgAuditStatus === OrderAuditStateEnum.UNREVIEWED) {
        item.value = '联络中';
        item.valueColor = colors.primary;
      }
    } else {
      item.stepIndex = 2;
      item.labelImg = suborder.orglogo;
      item.label = suborder.orgName;
      if (suborder.orgAuditStatus === OrderAuditStateEnum.REJECT) {
        item.value = '已驳回';
        item.valueColor = colors.error;
      }
      if (suborder.orgAuditStatus === OrderAuditStateEnum.UNREVIEWED) {
        item.value = '审核中';
        item.valueColor = colors.primary;
      }
    }
    item.label += ' 管理员';
    return item;
  }

  const timerRef = ref();
  const endTime = ref();
  function createTimer() {
    const pTime = props.paymentEndTime;
    if (!pTime) return;
    clearInterval(unref(timerRef));
    let timeObj = countDown(pTime);

    endTime.value = `剩余${timeObj.h}时${timeObj.m}分后关闭`;
    timerRef.value = setInterval(() => {
      let timeObj = countDown(pTime);
      if (timeObj.totalSecond <= 0) {
        endTime.value = '';
        emit('refresh');
        clearInterval(unref(timerRef));
      } else {
        endTime.value = `剩余${timeObj.h}时${timeObj.m}分后关闭`;
      }
    }, 10000);
  }

  onUnmounted(() => clearInterval(unref(timerRef)));
</script>

<style scoped lang="scss">
  .stepTips {
    display: flex;
    height: 100rpx;
    background-color: #fff4e7;
    border-radius: 20rpx;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    padding: 0 20rpx;
    color: #333;
    font-weight: 400;
  }

  .refusal-cause {
    font-size: 24rpx;
    min-height: 72rpx;
    border-top: 1px solid #f5f5f5;
  }
</style>
